<template>
  <div class="fault-report-container">
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" label-width="80px">
        <el-form-item label="报告日期">
          <el-date-picker
            v-model="searchForm.reportTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 280px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>故障状态分布</span>
            </div>
          </template>
          <div ref="faultStatusChart" style="width: 100%; height: 320px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>故障类型分布</span>
            </div>
          </template>
          <div ref="faultTypeChart" style="width: 100%; height: 320px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>设备故障数量排行</span>
            </div>
          </template>
          <div ref="deviceFaultCountChart" style="width: 100%; height: 320px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>月度故障趋势</span>
            </div>
          </template>
          <div ref="monthlyFaultTrendChart" style="width: 100%; height: 320px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useFaultStore } from '@/stores/modules/fault'; // 引入故障 Store
import { useDeviceStore } from '@/stores/modules/device'; // 引入设备 Store
import * as echarts from 'echarts';

// --- Pinia Store 实例 ---
const faultStore = useFaultStore();
const deviceStore = useDeviceStore();

// --- 搜索表单相关 ---
const searchForm = reactive({
  reportTimeRange: [], // 时间范围 [start, end]
});

const handleSearch = () => {
    fetchFaultStatistics();
};

const handleResetSearch = () => {
    searchForm.reportTimeRange = [];
    fetchFaultStatistics();
};

// --- ECharts 相关 ---
const faultStatusChart = ref(null);
const faultTypeChart = ref(null);
const deviceFaultCountChart = ref(null);
const monthlyFaultTrendChart = ref(null);

let charts = {}; // 存储所有 ECharts 实例

const initCharts = () => {
  nextTick(() => {
    charts.faultStatus = echarts.init(faultStatusChart.value);
    charts.faultType = echarts.init(faultTypeChart.value);
    charts.deviceFaultCount = echarts.init(deviceFaultCountChart.value);
    charts.monthlyFaultTrend = echarts.init(monthlyFaultTrendChart.value);

    Object.values(charts).forEach(chart => {
      chart.setOption({
        tooltip: { trigger: 'item' },
        series: []
      });
    });

    window.addEventListener('resize', resizeCharts);
  });
};

const resizeCharts = () => {
  Object.values(charts).forEach(chart => {
    chart?.resize();
  });
};

onMounted(() => {
  initCharts();
  fetchFaultStatistics(); 
});

onBeforeUnmount(() => { 
  Object.values(charts).forEach(chart => {
    chart?.dispose(); 
  });
  window.removeEventListener('resize', resizeCharts);
});

// 获取并处理统计数据
const fetchFaultStatistics = async () => {
  try {
    // 首先确保设备列表已加载，用于将 deviceId 映射为 deviceName
    if (deviceStore.deviceList.length === 0 || deviceStore.total === 0) {
        await deviceStore.fetchDeviceList({ pageNo: 1, pageSize: 99999 });
    }
    const deviceNameMap = new Map();
    deviceStore.deviceList.forEach(device => deviceNameMap.set(device.eqid, device.eqname));

    // 调用 faultStore 的 getFaultStatistics 方法获取原始数据 (已是前端格式)
    const res = await faultStore.getFaultStatistics(searchForm);
    if (res.code === true) { 
      const faultData = res.data.map(fault => ({
        ...fault,
        // 映射设备名称，因为 faultStore.fetchFaultList 已经做了初步映射
        // 这里是为了 double check 或处理一些 edge cases
        deviceName: fault.deviceName || deviceNameMap.get(fault.deviceId) || '未知设备' 
      }));

      if (faultData.length === 0) {
          ElMessage.info('当前筛选条件下无故障数据。');
          // 清空图表数据
          Object.values(charts).forEach(chart => {
              chart.setOption({ 
                series: [{ data: [], type: chart.getOption().series[0]?.type || 'pie' }], 
                xAxis: { data: [] }, 
                yAxis: {} 
              });
          });
          return;
      }
      updateChartOptions(faultData);
    } else {
      ElMessage.error(res.message || '获取故障统计数据失败');
    }
  } catch (error) {
    ElMessage.error('请求故障统计数据异常');
    console.error(error);
  }
};

const updateChartOptions = (faultData) => {
  // 1. 故障状态分布 (饼图)
  const statusCounts = faultData.reduce((acc, fault) => {
    acc[fault.status] = (acc[fault.status] || 0) + 1;
    return acc;
  }, {});
  const statusChartData = Object.keys(faultStore.FaultStatusMap).map(statusKey => ({ 
    name: faultStore.FaultStatusMap[statusKey].label,
    value: statusCounts[faultStore.FaultStatusMap[statusKey].label] || 0 // 使用 label 键
  }));
  charts.faultStatus.setOption({
    title: { text: null }, 
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: Object.keys(faultStore.FaultStatusMap).map(key => faultStore.FaultStatusMap[key].label),
    },
    series: [
      {
        name: '故障状态',
        type: 'pie',
        radius: '60%',
        center: ['65%', '50%'],
        data: statusChartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        color: [
          faultStore.FaultStatusMap['待处理'].tagType === 'danger' ? '#F56C6C' : '',
          faultStore.FaultStatusMap['处理中'].tagType === 'warning' ? '#E6A23C' : '',
          faultStore.FaultStatusMap['已解决'].tagType === 'success' ? '#67C23A' : '',
          faultStore.FaultStatusMap['已关闭'].tagType === 'info' ? '#909399' : ''
        ].filter(Boolean) 
      }
    ]
  });

  // 2. 故障类型分布 (饼图)
  const typeCounts = faultData.reduce((acc, fault) => {
    if (fault.faultType) { // 确保 faultType 存在
      acc[fault.faultType] = (acc[fault.faultType] || 0) + 1;
    }
    return acc;
  }, {});
  const typeLabels = Object.keys(typeCounts).filter(Boolean); // 过滤空键
  const typeChartData = typeLabels.map(type => ({
    name: type,
    value: typeCounts[type]
  }));
  charts.faultType.setOption({
    title: { text: null },
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: typeLabels,
    },
    series: [
      {
        name: '故障类型',
        type: 'pie',
        radius: '60%',
        center: ['65%', '50%'],
        data: typeChartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });

  // 3. 设备故障数量排行 (柱状图)
  const deviceFaultCountsMap = faultData.reduce((acc, fault) => {
    if (fault.deviceName) {
      acc[fault.deviceName] = (acc[fault.deviceName] || 0) + 1;
    }
    return acc;
  }, {});
  const deviceNames = Object.keys(deviceFaultCountsMap).sort((a, b) => deviceFaultCountsMap[b] - deviceFaultCountsMap[a]);
  const deviceFaultValues = deviceNames.map(name => deviceFaultCountsMap[name]);

  charts.deviceFaultCount.setOption({
    title: { text: null },
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    xAxis: {
      type: 'category',
      data: deviceNames,
      axisLabel: {
        interval: 0, 
        rotate: deviceNames.length > 5 ? 30 : 0 
      }
    },
    yAxis: {
      type: 'value',
      name: '故障次数',
      minInterval: 1 
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%', 
      containLabel: true
    },
    series: [
      {
        name: '故障次数',
        type: 'bar',
        data: deviceFaultValues,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  });

  // 4. 月度故障趋势 (折线图)
  const monthlyCountsMap = faultData.reduce((acc, fault) => {
    const month = fault.reportTime ? fault.reportTime.substring(0, 7) : 'Invalid Date'; 
    acc[month] = (acc[month] || 0) + 1;
    return acc;
  }, {});
  const months = Object.keys(monthlyCountsMap).sort(); 
  const monthlyFaultValues = months.map(month => monthlyCountsMap[month]);

  charts.monthlyFaultTrend.setOption({
    title: { text: null },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: months,
      boundaryGap: false 
    },
    yAxis: {
      type: 'value',
      name: '故障次数',
      minInterval: 1 
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    series: [
      {
        name: '故障次数',
        type: 'line',
        data: monthlyFaultValues,
        smooth: true, 
        areaStyle: { 
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(56, 151, 237, 0.4)' },
            { offset: 1, color: 'rgba(56, 151, 237, 0)' }
          ])
        },
        lineStyle: {
          color: '#3897ed'
        },
        itemStyle: {
          color: '#3897ed'
        }
      }
    ]
  });
};

</script>

<style scoped>
.fault-report-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

.search-card {
  margin-bottom: 20px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}
</style>
